package small.common.statistic.data;

/**
 * 窗口
 *
 * @author jinzhou
 * @data 2023/4/7 13:28
 */
public class WindowWrap<T> {

    /**
     * 窗口长度
     */
    private final long windowLengthInMs;

    /**
     * 窗口开始时间戳
     */
    private long windowStart;

    /**
     * 窗口统计数据
     */
    private T value;

    public WindowWrap(long windowLengthInMs, long windowStart, T value) {
        this.windowLengthInMs = windowLengthInMs;
        this.windowStart = windowStart;
        this.value = value;
    }

    public long windowLength() {
        return windowLengthInMs;
    }

    public long windowStart() {
        return windowStart;
    }

    public T value() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    /**
     * 重置开始时间戳
     */
    public WindowWrap<T> resetTo(long startTime) {
        this.windowStart = startTime;
        return this;
    }

    /**
     * 判断时间戳是否在当前窗口
     * 开始时间小于当前时间 并且 当前时间在窗口间隔内（当前时间小于开始时间+时间间隔）
     */
    public boolean isTimeInWindow(long timeMillis) {
        return windowStart <= timeMillis && timeMillis < windowStart + windowLengthInMs;
    }

    @Override
    public String toString() {
        return "WindowWrap{" +
                "windowLengthInMs=" + windowLengthInMs +
                ", windowStart=" + windowStart +
                ", value=" + value +
                '}';
    }
}
